using micromsg;
using MicroMsg.Common.Algorithm;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Network;
using MicroMsg.Protocol;
using MicroMsg.Storage;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
namespace MicroMsg.Scene
{
	public class NetSceneUploadHDHeadImg : NetSceneBaseEx<UploadHDHeadImgRequest, UploadHDHeadImgResponse, UploadHDHeadImgRequest.Builder>
	{
		private const string TAG = "NetSceneUploadHDHeadImg";
		private const int ONE_2GPACK_UPLOADSIZE = 8192;
		private const int ONE_3GPACK_UPLOADSIZE = 16384;
		private const int ONE_WIFIPACK_UPLOADSIZE = 32768;
		private const int MAX_2G_UPLOADTIMES = 52;
		private const int MAX_3G_UPLOADTIMES = 26;
		private const int MAX_WIFI_UPLOADTIMES = 13;
		private int mUploadTimes;
		private Stream srcHeadImgStream;
		private uint nStartPos;
		private int mTotalLen;
		private int mDataLen;
		private int mTransLen;
		private string selfUserName;
		private int mHeadImgType = 1;
		private int mMaxUplaodTimes = 52;
		private int mUpLoadedSize = 8192;
		private string strImageHash = "";
		public bool doScene(Stream headImgStream, int headImgType)
		{
			return new NetSceneUploadHDHeadImg().doSceneEx(headImgStream, headImgType);
		}
		private bool doSceneEx(Stream headImgStream, int headImgType)
		{
			if (headImgStream == null)
			{
				return false;
			}
			this.srcHeadImgStream = this.compressImg(headImgStream);
			if (this.srcHeadImgStream == null)
			{
				this.srcHeadImgStream = headImgStream;
			}
			this.mTotalLen = (int)this.srcHeadImgStream.get_Length();
			if (this.mTotalLen <= 0)
			{
				return false;
			}
			if (headImgType > 0)
			{
				this.mHeadImgType = headImgType;
			}
			if (this.mHeadImgType == 2)
			{
				this.selfUserName = AccountMgr.getCurAccount().strUsrName + ConstantValue.TAG_BOTTLE;
			}
			else
			{
				this.selfUserName = AccountMgr.getCurAccount().strUsrName;
			}
			this.mUpLoadedSize = this.getSendPackSize();
			this.strImageHash = MD5Core.GetHashString(Util.getNowMilliseconds() + this.selfUserName);
			return this.doScene();
		}
		private bool doScene()
		{
			if (this.srcHeadImgStream != null && !string.IsNullOrEmpty(this.selfUserName))
			{
				this.mDataLen = this.mTotalLen - (int)this.nStartPos;
				if (this.mDataLen > this.mUpLoadedSize)
				{
					this.mDataLen = this.mUpLoadedSize;
				}
				byte[] inBytes = this.readFromStream((int)this.nStartPos, this.mDataLen);
				base.beginBuilder();
				this.mBuilder.BaseRequest = NetSceneBase.makeBaseRequest(0);
				this.mBuilder.TotalLen = (uint)this.mTotalLen;
				this.mBuilder.StartPos = this.nStartPos;
				this.mBuilder.HeadImgType = (uint)this.mHeadImgType;
				this.mBuilder.ImgHash = this.strImageHash;
				this.mBuilder.Data = Util.toSKBuffer(inBytes);
				this.mSessionPack.mConnectMode = 2;
				this.mSessionPack.mCmdUri = "/cgi-bin/micromsg-bin/uploadhdheadimg";
				base.endBuilder();
				this.mUploadTimes++;
				return true;
			}
			return false;
		}
		protected override void onFailed(UploadHDHeadImgRequest request, UploadHDHeadImgResponse response)
		{
			Log.smethod_1("NetSceneUploadHDHeadImg", "send UploadHDHeadImgRequest failed");
			this.doSceneFinished(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_ERR);
		}
		protected override void onSuccess(UploadHDHeadImgRequest request, UploadHDHeadImgResponse response)
		{
			if (response == null)
			{
				return;
			}
			RetConst ret = (RetConst)response.BaseResponse.Ret;
			if (ret != RetConst.MM_OK)
			{
				Log.smethod_1("NetSceneUploadHDHeadImg", "send UploadHDHeadImgRequest failed ret =" + ret);
				this.doSceneFinished(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_ERR);
				return;
			}
			this.mTransLen += this.mDataLen;
			if (this.isUploadCompleted(response))
			{
				this.writeTofile();
				if (this.mHeadImgType == 1)
				{
					AccountMgr.getCurAccount().strHDheadImgVersion = response.FinalImgMd5Sum;
				}
				else
				{
					AccountMgr.getCurAccount().strBottleHDheadImgVersion = response.FinalImgMd5Sum;
				}
				AccountMgr.updateAccount();
				this.doSceneFinished(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_SUCCESS);
				return;
			}
			uint arg_9F_0 = response.StartPos;
			if (response.TotalLen > 0u && response.StartPos >= this.nStartPos && response.StartPos < response.TotalLen && this.mTotalLen > 0 && this.mUploadTimes <= this.mMaxUplaodTimes)
			{
				this.nStartPos = response.StartPos;
				this.doScene();
				return;
			}
			Log.smethod_1("NetSceneUploadHDHeadImg", "Send image failed because of response error");
			this.logErrorParam(response);
			this.doSceneFinished(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_ERR);
		}
		private void logErrorParam(UploadHDHeadImgResponse resp)
		{
			Log.smethod_1("NetSceneUploadHDHeadImg", "Send image failed because of response param error");
			Log.smethod_1("NetSceneUploadHDHeadImg", "response.StartPos = " + resp.StartPos);
			Log.smethod_1("NetSceneUploadHDHeadImg", "response.TotalLen = " + resp.TotalLen);
			Log.smethod_1("NetSceneUploadHDHeadImg", "mTotalLen = " + this.mTotalLen);
			Log.smethod_1("NetSceneUploadHDHeadImg", "nStartPos = " + this.nStartPos);
			Log.smethod_1("NetSceneUploadHDHeadImg", "mUploadTimes = " + this.mUploadTimes);
			Log.smethod_1("NetSceneUploadHDHeadImg", "mMaxUplaodTimes = " + this.mMaxUplaodTimes);
			Log.smethod_1("NetSceneUploadHDHeadImg", "mTransLen = " + this.mTransLen);
			Log.smethod_1("NetSceneUploadHDHeadImg", "mDataLen = " + this.mDataLen);
		}
		private bool isUploadCompleted(UploadHDHeadImgResponse resp)
		{
			return this.mTotalLen > 0 && (this.mTransLen >= this.mTotalLen || (ulong)resp.StartPos >= (ulong)((long)this.mTotalLen));
		}
		public bool writeTofile()
		{
			IsolatedStorageFileStream isolatedStorageFileStream = this.openFile();
			bool result;
			try
			{
				byte[] array = new byte[this.srcHeadImgStream.get_Length()];
				this.srcHeadImgStream.set_Position(0L);
				int num = this.srcHeadImgStream.Read(array, 0, (int)this.srcHeadImgStream.get_Length());
				if ((long)num != this.srcHeadImgStream.get_Length())
				{
					Log.smethod_1("NetSceneUploadHDHeadImg", "save HDheadimg failed");
					isolatedStorageFileStream.Close();
					result = false;
				}
				else
				{
					isolatedStorageFileStream.Seek(0L, 0);
					isolatedStorageFileStream.Write(array, 0, array.Length);
					isolatedStorageFileStream.Close();
					result = true;
				}
			}
			catch (Exception ex)
			{
				Log.smethod_1("NetSceneUploadHDHeadImg", ex.get_Message());
				isolatedStorageFileStream.Close();
				result = false;
			}
			return result;
		}
		public void doSceneFinished(EventConst eventConst_0)
		{
			if (eventConst_0 == EventConst.ON_NETSCENE_UPLOAD_HEADIMG_ERR)
			{
				EventCenter.postEvent(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_ERR, null, null);
			}
			else
			{
				if (eventConst_0 == EventConst.ON_NETSCENE_UPLOAD_HEADIMG_SUCCESS)
				{
					EventCenter.postEvent(EventConst.ON_NETSCENE_UPLOAD_HEADIMG_SUCCESS, null, null);
				}
			}
			this.srcHeadImgStream.Close();
		}
		private byte[] readFromStream(int startPos, int dataLen)
		{
			byte[] result;
			try
			{
				if (this.srcHeadImgStream == null)
				{
					result = null;
				}
				else
				{
					byte[] array = new byte[dataLen];
					this.srcHeadImgStream.Seek((long)startPos, 0);
					int num = this.srcHeadImgStream.Read(array, 0, dataLen);
					if (num <= 0)
					{
						Log.smethod_1("NetSceneUploadHDHeadImg", "read from stream lenght = " + num);
						result = null;
					}
					else
					{
						Log.smethod_5("NetSceneUploadHDHeadImg", "read length " + num);
						result = array;
					}
				}
			}
			catch (Exception ex)
			{
				Log.smethod_1("NetSceneUploadHDHeadImg", ex.get_Message());
				result = null;
			}
			return result;
		}
		private Stream compressImg(Stream headImgStream)
		{
			Stream result;
			try
			{
				BitmapImage bitmapImage = new BitmapImage();
				bitmapImage.SetSource(headImgStream);
				WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
				MemoryStream memoryStream = new MemoryStream();
				Extensions.SaveJpeg(writeableBitmap, memoryStream, bitmapImage.get_PixelWidth(), bitmapImage.get_PixelHeight(), 0, 70);
				result = memoryStream;
			}
			catch (Exception ex)
			{
				Log.smethod_1("NetSceneUploadHDHeadImg", ex.ToString());
				result = null;
			}
			return result;
		}
		private IsolatedStorageFileStream openFile()
		{
			if (string.IsNullOrEmpty(this.selfUserName))
			{
				return null;
			}
			IsolatedStorageFileStream result;
			try
			{
				using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
				{
					if (!userStoreForApplication.DirectoryExists(StorageIO.getHeadImgHDPath()))
					{
						userStoreForApplication.CreateDirectory(StorageIO.getHeadImgHDPath());
					}
					string path = StorageMgr.hdheadimg.getPath(this.selfUserName);
					if (string.IsNullOrEmpty(path))
					{
						result = null;
					}
					else
					{
						if (userStoreForApplication.FileExists(path))
						{
							userStoreForApplication.DeleteFile(path);
						}
						IsolatedStorageFileStream isolatedStorageFileStream = userStoreForApplication.CreateFile(path);
						result = isolatedStorageFileStream;
					}
				}
			}
			catch (Exception ex)
			{
				Log.smethod_1("NetSceneUploadHDHeadImg", ex.get_Message());
				result = null;
			}
			return result;
		}
		public int getSendPackSize()
		{
			if (NetworkDeviceWatcher.isCurrentWifi())
			{
				Log.smethod_4("NetSceneUploadHDHeadImg", "Current net is Wifi");
				this.mMaxUplaodTimes = 13;
				return 32768;
			}
			if (NetworkDeviceWatcher.isCurrentCell3G())
			{
				Log.smethod_4("NetSceneUploadHDHeadImg", "Current net is 3G");
				this.mMaxUplaodTimes = 26;
				return 16384;
			}
			if (NetworkDeviceWatcher.isCurrentCell2G())
			{
				Log.smethod_4("NetSceneUploadHDHeadImg", "Current net is 2G");
				this.mMaxUplaodTimes = 52;
				return 8192;
			}
			Log.smethod_4("NetSceneUploadHDHeadImg", "Current net is UnKnow");
			this.mMaxUplaodTimes = 26;
			return 16384;
		}
	}
}
